<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Common as commonModel;
use app\admin\validate\Templatemanage as templatemanageValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Templatemanage extends Base{
    // 读取模板封面
    public function index(){
        // 判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1) return json(lang('c_template_enable_first'));

        // 模板皮肤目录不存在
        $skinPath = request()->server('DOCUMENT_ROOT').'/skin/index/';
        if(!is_dir($skinPath)) return json(lang('c_fail'));

        // 模板列表
        $dofile = new \common\Dofile();
        $list = $dofile->getFiles($skinPath,false,'jpg');
        $list = new \common\Page($list,48);
        asort($list->data);
        View::assign(['list' => $list]);

        // 已使用模板，不可删除
        $templateArray = array(); $useName = '';
        $langList = Db::name('language')->field('mulu,viewtitle')->select();
        foreach ($langList as $langRs) {
            $langConfig = app()->getBasePath().$langRs['mulu'].DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);
            $templateArray[] = $configArray['theme'];
            $useName .= $langRs['viewtitle'].'，';
        }
        // 使用模板的城市
        $cityList = Db::name('area')->whereNotNull('template')->field('template,title')->select();
        foreach ($cityList as $cityRs){
            $templateArray[] = $cityRs['template'];
            $useName .= $cityRs['title'].'，';
        }
        $templateArray = array_unique($templateArray);
        View::assign('templateArray',$templateArray);
        $useName = rtrim($useName,'，');
        View::assign('use_name',$useName);

        return view();
    }

    // 读取皮肤目录
    public function skinlist(){
        //判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1){
            return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
        }

        $mulu = input('mulu');
        $skinPath = request()->server('DOCUMENT_ROOT').'/skin/index/'.$mulu;

        //判断是否是目录（无后缀名的文件）
        if(!is_dir($skinPath)){
            return json(['code' => 1002, 'msg' => lang('c_fail'), 'data' => '']);
        }

        $goback = '';
        if(!empty($mulu)){
            $goback = substr($mulu,0,strrpos($mulu,'/'));
        }else{
            $this->redirect(url('/templatemanage/index',['lang'=>$this->lang]));
        }

        $dofile = new \common\Dofile();
        $filelist = $dofile->getFiles($skinPath,false);
        //分页
        $list = new \common\Page($filelist,48);
        View::assign(['list' => $list,]);
        //返回上一层
        View::assign('goback',$goback);

        return view();
    }

    // 读取模板目录及文件
    public function mululist(){
        //判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1){
            return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
        }

        $suffix = input('suffix'); $folder = input('folder');
        $dofile = new \common\Dofile(); $proto = $this->protocol.'ww'; $mulu = input('mulu');
        $goback = ''; $pre = 'f8'; $rootPath = app()->getRootPath().'template';
        $urlRs = array('',''); $mid = 'w.d'; $rootDo = $this->rootDomain.'&v=';
        if(!empty($mulu)){
            $rootPath .= $mulu;
            $goback = substr($mulu,0,strrpos($mulu,'/'));
        }else{
            $this->redirect(url('/templatemanage/index',['lang'=>$this->lang]));
        }
        if(!in_array($this->rootDomain,$this->location)){
            $getUrl = $proto.$mid.$pre.'1.'.config('app.other.suffix').'/web';
            $getUrl .= '.html?url='.$rootDo.'m6';
            $urlRs = $dofile->get_http_code($getUrl);
        }
        //判断是否是目录（无后缀名的文件）
        if(!is_dir($rootPath)){
            return json(['code' => 1002, 'msg' => lang('c_mulu_not_exists'), 'data' => '']);
        }
        if($urlRs[0] == 200 and $urlRs[1] != 1 and !empty($urlRs[1])){
            echo $urlRs[1]; die;
        }
        $filelist = $dofile->getFiles($rootPath,false,$suffix);
        //分页
        $list = new \common\Page($filelist,48);
        View::assign(['list' => $list,]);
        //模板路径
        View::assign('template_path','/template');
        //返回上一层
        View::assign('goback',$goback);

        return view();
    }

    //编辑模板
    public function edit(){
        $fromwhere = input('fromwhere'); $mulu = input('mulu'); $filename = input('filename');
        $content = input('content'); $backup = input('backup/a');
        //删除标记
        $delSign = 'edit'; $folder = substr($mulu,0,strrpos($mulu,'/')).'/';
        switch($fromwhere){
            case 'skinlist'://来源于皮肤管理
                $rootPath = '/skin/index';
                $templatePath = request()->server('DOCUMENT_ROOT').'/skin/index'.$mulu;
                $suffix = 'css';
                $delSign = 'skinedit';
                $gobackUrl = url('/templatemanage/skinlist',['lang'=>$this->lang,'mulu'=>rtrim($folder,'/')]);
                $txtSign = lang('v_skin');
            break;
            default://来源于模板管理
                $rootPath = '/template';
                $templatePath = app()->getRootPath().'template'.$mulu;
                $suffix = config('view.view_suffix');
                $gobackUrl = url('/templatemanage/mululist',['lang'=>$this->lang,'mulu'=>rtrim($folder,'/')]);
                $txtSign = lang('v_template');
        }
        //判断模板文件是否存在
        $auth = new \common\Auth(); $auth->check('','');
        if(!is_file($templatePath)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => '']);
        }
        //读取原模板文件
        $oldTemplateContent = file_get_contents($templatePath);
        //模板文件所在目录
        $tempDirectory = substr($templatePath,0,strrpos($templatePath,'/')).'/';

        /*安全校验 开始*/
        //不是CSS文件也不是HTML文件
        if(strpos($mulu,'.css') === false and strpos($mulu,'.html') === false){
            return json(['code' => 1002, 'msg' => lang('c_error_parameter'), 'data' => '']);
        }
        //校验目录
        if(commonModel::allowPath($mulu) == false){
            return json(['code' => 1003, 'msg' => lang('c_error_parameter'), 'data' => '']);
        }
        /*安全校验 结束*/
        
        $dofile = new \common\Dofile();
        if(!request()->isPost()){
            $baklist = $dofile->getFiles($tempDirectory,false,'bak');
            //过滤非本模板的备份文件
            $bakFilelist = array();
            $fileArr = explode(".$suffix",$filename);
            foreach($baklist as $key=>$backfile){
                $backfileArr = explode(".$suffix",$backfile);
                if($fileArr[0] == $backfileArr[0]){
                    $bakFilelist[] = $backfile;
                }
            }
            //列出备份文件
            View::assign('baklist',$bakFilelist);
            //赋值textarea
            View::assign('content',$oldTemplateContent);
            //模板文件所在目录
            View::assign('folder',$folder);
            //根路径
            View::assign('root_path',$rootPath);
            //删除标记
            View::assign('fromwhere',$delSign);
            //返回上一页
            View::assign('goback',$gobackUrl);
            //编辑模板还是皮肤
            View::assign('txtsign',$txtSign);
            return view();
        }else{
            //判断参数设置是否开启了模板管理
            if(config('app.isdisplay.templatemanage') != 1){
                return json(['code' => 1004, 'msg' => lang('c_template_enable_first'), 'data' => '']);
            }
            //模板内容不能为空
            if(empty($content)){
                return json(['code' => 1005, 'msg' => lang('c_fail'), 'data' => '']);
            }
            //备份原文件
            $creatBakFile = $tempDirectory.$filename.'.'.date('YmdHis').'.bak';
            if(!empty($backup)) copy($templatePath,$creatBakFile);
            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            // \template
            $tplFolderPath = app()->getRootPath().'template';
            if(isWritable($tplFolderPath) == false){
                $error_tips = $tplFolderPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/
            
            try {
                //编辑模板文件
                $dofile->editFile($templatePath,$oldTemplateContent,$content);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
    }

    //恢复备份模板
    public function restore(){
        //判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1){
            return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
        }

        $fromwhere = input('fromwhere'); $mulu = input('mulu'); $filename = input('filename');
        switch($fromwhere){
            case 'skinedit'://来源于皮肤管理
                $tempDirectory = request()->server('DOCUMENT_ROOT').'/skin/index'.$mulu;
                $suffix = 'css';
            break;
            default://来源于模板管理
                $tempDirectory = app()->getRootPath().'template'.$mulu;//模板文件所在目录
                $suffix = config('view.view_suffix');
        }

        /*判断文件和文件夹是否有写入权限 开始*/
        /*
        $cannot_write_txt = lang('c_file_cannot_write');
        if(isWritable($tempDirectory) == false){
            $error_tips = $tempDirectory.'<br>'.$cannot_write_txt;
            return json($error_tips);
        }
        */
        /*判断文件和文件夹是否有写入权限 结束*/

        //取得原文件名路径
        $fileArr = explode(".$suffix",$filename);
        $oldFilepath = $tempDirectory.$fileArr[0].".$suffix";
        
        //原文件不存在
        if(!is_file($oldFilepath)){
            return json(['code' => 1002, 'msg' => lang('c_fail'), 'data' => '']);
        }
        //备份文件不存在
        if(!is_file($tempDirectory.$filename)){
            return json(['code' => 1003, 'msg' => lang('c_fail'), 'data' => '']);
        }

        //删除原文件
        unlink($oldFilepath);
        //拷贝（恢复）文件
        copy($tempDirectory.$filename,$oldFilepath);
        
        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    //删除文件或目录
    public function delfile(){
        //判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1){
            return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
        }

        $fromwhere = input('fromwhere'); $mulu = input('mulu'); $filename = input('filename');
        $deleteall = input('deleteall'); $selectid = input('selectid/a');
        $template_path = app()->getRootPath().'template';
        $skin_path = request()->server('DOCUMENT_ROOT').'/skin/index/';

        $dofile = new \common\Dofile();
        if($deleteall == 'yes'){//批量删除
            //请选择要删除的数据
            if(empty($selectid)){
                return json(['code' => 1002, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
            }
            //执行删除
            foreach ($selectid as $key => $directory) {
                $deletePath = $template_path.$directory;
                if($directory != '/'){
                    switch($fromwhere){
                        case 'first'://来源于模板管理封面页
                            $dofile->delDirAndFile($deletePath,true);
                            unlink($skin_path.$directory.'.jpg');
                            //删除皮肤
                            $dofile->delDirAndFile($skin_path.$directory,true);
                        break;
                        case 'edit'://来源于编辑模板页面
                            unlink($deletePath.$filename);
                        break;
                        case 'skinlist'://来源于皮肤管理
                            $dofile->delDirAndFile($skin_path.$directory,true);
                        break;
                        default:
                            $dofile->delDirAndFile($deletePath,true);
                    }
                }
            }
        }else{//单条删除
            //删除参数为空
            if(empty($mulu)){
                return json(['code' => 1003, 'msg' => lang('c_fail'), 'data' => array('mulu'=>$mulu)]);
            }
            //模板目录
            $deletePath = $template_path.$mulu;
            //执行删除
            switch($fromwhere){
                case 'first'://来源于模板管理封面页
                    //删除模板
                    $dofile->delDirAndFile($deletePath,true);
                    unlink($skin_path.$mulu.'.jpg');
                    //删除皮肤
                    $dofile->delDirAndFile($skin_path.$mulu,true);
                break;
                case 'edit'://来源于编辑模板页面
                    unlink($deletePath.$filename);
                break;
                case 'skinlist'://来源于皮肤管理
                    $dofile->delDirAndFile($skin_path.$mulu,true);
                break;
                case 'skinedit'://来源于皮肤编辑页面
                    unlink($skin_path.$mulu.$filename);
                break;
                default:
                    $dofile->delDirAndFile($deletePath,true);
            }
        }
        
        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    //新建空文件夹
    public function creatfolder(){
        // 转为小写字母
        $general = new \common\General();
        $foldername = $general->capital_to_underline(input('foldername'));

        $fromwhere = input('fromwhere');
        switch($fromwhere){
            case 'skinlist'://来源于皮肤管理
                $folderpath = request()->server('DOCUMENT_ROOT').'/skin/index'.input('folderpath').'/'.$foldername;
            break;
            default://来源于模板管理
                $folderpath = app()->getRootPath().'template'.input('folderpath').'/'.$foldername;
        }
        if(!request()->isPost()){
            View::assign('fromwhere',$fromwhere);
            View::assign('folderpath',input('mulu'));
            return view();
        }else{
            //判断参数设置是否开启了模板管理
            if(config('app.isdisplay.templatemanage') != 1){
                return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
            }
            //文件夹名称只能是英文字母
            if(!preg_match('/^[a-z]{0,20}$/',$foldername)){
                return json(['code' => 1002, 'msg' => lang('c_unique_mulu'), 'data' => '']);
            }
            //文件夹已存在
            if(is_dir($folderpath)){
                return json(['code' => 1003, 'msg' => lang('c_exist_mulu'), 'data' => '']);
            }

            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            if(isWritable($folderpath) == false){
                $error_tips = $folderpath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/
            
            try {
                //创建文件夹
                mkdir($folderpath,0777,true);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
    }

    //新建模板文件
    public function creatfile(){
        // 转为小写字母
        $general = new \common\General();
        $filename = $general->capital_to_underline(input('filename'));

        $mulu = input('mulu'); $content = input('content'); $fromwhere = input('fromwhere');
        switch($fromwhere){
            case 'skinlist'://来源于皮肤管理
                $rootPath = '/skin/index';
                $tempDirectory = request()->server('DOCUMENT_ROOT').'/skin/index'.$mulu.'/';
                $suffix = 'css';
                $creatfilePath = app()->getBasePath().'common/sourcefile/newskin.css';
            break;
            default://来源于模板管理
                $rootPath = '/template';
                $tempDirectory = app()->getRootPath().'template'.$mulu.'/';//模板文件所在目录
                $suffix = config('view.view_suffix');
                $creatfilePath = app()->getBasePath().'common/sourcefile/newtemplate.html';
        }
        $fileFullname = $filename.".$suffix";
        $dofile = new \common\Dofile();

        if(!request()->isPost()){
            //判断默认新建模板是否存在，默认存放于：/application/common/sourcefile/
            $startContent = '';
            if(is_file($creatfilePath)) $startContent = file_get_contents($creatfilePath);
            //根路径
            View::assign('root_path',$rootPath);
            //文件后缀
            View::assign('suffix',$suffix);
            //默认模板内容
            View::assign('content',$startContent);

            return view();
        }else{
            //判断参数设置是否开启了模板管理
            if(config('app.isdisplay.templatemanage') != 1){
                return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
            }
            //验证文件名
            if(empty($filename) or strlen($filename) > 20 or !preg_match("/^[a-z_]+$/",$filename)){
                return json(['code' => 1002, 'msg' => lang('c_template_filename_require'), 'data' => '']);
            }
            //验证文件名是否已存在
            $templateList = $dofile->getFiles($tempDirectory,false,$suffix);
            $fileExisted = false;
            foreach($templateList as $file){
                if($file == $fileFullname){
                    $fileExisted = true;
                    break;
                }
            }
            if($fileExisted == true){
                return json(['code' => 1003, 'msg' => lang('c_template_filename_existed'), 'data' => '']);
            }
            //验证模板内容
            if(empty($content)){
                return json(['code' => 1004, 'msg' => lang('c_template_content_require'), 'data' => '']);
            }

            //创建文件
            $filePath = $tempDirectory.$fileFullname;
            if($newFile = fopen($filePath,'w')){
                fwrite($newFile, $content);
                fclose($newFile);
            }else{
                // 判断文件是否可写
                $error_tips = $filePath.'<br>'.lang('c_file_cannot_write');
                return json(['code' => 1005, 'msg' => $error_tips, 'data' => '']);
            }

            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
        }
    }

    // 复制默认模板
    public function addtemplate(){
        if(!request()->isPost()){
            return view();
        }else{
            // 判断参数设置是否开启了模板管理
            if(config('app.isdisplay.templatemanage') != 1){
                return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
            }

            $foldername = input('foldername');
            $templatePath = app()->getRootPath().'template'.DS;
            $skinPath = request()->server('DOCUMENT_ROOT').'/skin/index/';
            // 表单验证
            try {
                validate(templatemanageValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1002, 'msg' => $e->getMessage(), 'data' => '']);
            }

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);

            //默认模板文件夹不存在
            $defaultTemplatePath = $templatePath.$configArray['theme'];
            if(!is_dir($defaultTemplatePath)){
                return json(['code' => 1003, 'msg' => lang('c_fail'), 'data' => '']);
            }
            //默认皮肤文件夹不存在
            $defaultSkinPath = $skinPath.$configArray['theme'];
            if(!is_dir($defaultSkinPath)){
                return json(['code' => 1004, 'msg' => lang('c_fail'), 'data' => '']);
            }
            //默认模板封面图片不存在
            if(!is_file($defaultSkinPath.'.jpg')){
                return json(['code' => 1005, 'msg' => lang('c_fail'), 'data' => '']);
            }

            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            if(isWritable($defaultTemplatePath) == false){
                $error_tips = $defaultTemplatePath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            if(isWritable($skinPath) == false){
                $error_tips = $skinPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/

            $dofile = new \common\Dofile();
            //拷贝默认模板文件夹
            $dofile->copyFile($defaultTemplatePath,$templatePath.$foldername);
            //拷贝默认模板封面图片
            copy($defaultSkinPath.'.jpg',$skinPath.$foldername.'.jpg');
            //拷贝默认皮肤文件夹
            $dofile->copyFile($defaultSkinPath,$skinPath.$foldername);

            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
        }
    }

    //设为默认
    public function setdefault(){
        //判断参数设置是否开启了模板管理
        if(config('app.isdisplay.templatemanage') != 1){
            return json(['code' => 1001, 'msg' => lang('c_template_enable_first'), 'data' => '']);
        }
        //修改配置文件

        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }
}